package com.fmsz.physicalheadline.adapter.top;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.v4.util.Pair;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.fmsz.physicalheadline.R;
import com.fmsz.physicalheadline.databinding.DynamicItemBinding;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/12/29.
 */

public class TopRecycleAdapter<D> extends RecyclerView.Adapter<TopRecycleAdapter.ViewHolder>{

    private List<D> list;
    private Map<Class<?>,Pair<Integer,Integer>> map;
    private Context context;

    public TopRecycleAdapter(Context context,List<D> list, Map<Class<?>, Pair<Integer, Integer>> map) {
        this.context = context;
        this.list = list;
        this.map = map;
    }

    @Override
    public int getItemViewType(int position) {
        if (map.size()==1) {
            return map.get(null).first;
        }else{
            return map.get(list.get(position).getClass()).first;
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        ViewHolder holder = new ViewHolder(DataBindingUtil.inflate(LayoutInflater.from(context), viewType, parent, false));
//        View play_btn = ((DynamicItemBinding) holder.binding).gridLayout.findViewById(R.id.play_btn);
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        D d = list.get(position);
        Pair<Integer,Integer> pair;
        if (map.size()==1) {
            pair = map.get(null);
        }else{
            pair = map.get(d.getClass());
        }
        holder.binding.setVariable(pair.second,d);
    }
    public void add(D d){
        add(list.size(),d);
    }

    private void add(int position, D d) {
        if (d==null) {
            return;
        }
        list.add(position,d);
        notifyItemInserted(position);
    }
    public void addAll(Collection<? extends D> collection){
        addAll(list.size(),collection);
    }

    private void addAll(int position, Collection<? extends D> collection) {
        if (collection==null) {
            return;
        }
        list.addAll(position,collection);
        notifyItemRangeInserted(position,collection.size());
    }


    @Override
    public int getItemCount() {
        return list.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        private ViewDataBinding binding;
        public ViewHolder(ViewDataBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }
}
